import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { loadData, toggle } from "../store/features/todosSlice";

export default function TodoList() {
  const todos = useSelector((state) => state.todos);
  const dispatch = useDispatch();

  function handleChange(id) {
    dispatch(toggle(id));
  }

  useEffect(() => {
    dispatch(loadData());
    // console.log(loadData());
  }, []);

  return (
    <div>
      <h1>TodoList</h1>
      <ul>
        {todos.map((item) => {
          return (
            <li key={item.id} onClick={() => handleChange(item.id)}>
              {item.text}
              <input
                type="checkbox"
                checked={item.done}
                onClick={(event) => {
                  event.stopPropagation();
                }}
                onChange={(event) => {
                  event.stopPropagation(); // 阻止冒泡
                  handleChange(item.id);
                }}
              />
            </li>
          );
        })}
      </ul>
    </div>
  );
}
